package controller;

import org.apache.commons.codec.binary.Base64;
import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;

import javax.crypto.Cipher;
import java.security.KeyFactory;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.Signature;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;

/**
 * Created by PCG on 2016/4/29.
 */
public class TestController {


    public static void main(String[] args) throws Exception{
        String PRIVATE_KEY = "MIICdwIBADANBgkqhkiG9w0BAQEFAASCAmEwggJdAgEAAoGBAKNcYWPtRf6KIc46" +
                "oSQgmLJXbigVglpCZS9KczOuxd2hBj86/g7cOzrJPzFmvh7tWLK2W1tCG1fa7h0E" +
                "EfTzwChjEgllZYg78udel6jf84LpZVUsR3L1ho76E/UhhgKnNFW8cAEP1UulTssP" +
                "OwytOM45O5TzpZMtiEsF8juykSePAgMBAAECgYBmkzg35aHgrV2Cv/+0zp7yxMFP" +
                "fAoIoM4mPqpNln15p4VjqKgkLpcmV31NiMTyaHgcZzK//6dpp/eB0q9vzqol8OC1" +
                "WhNWJjuQpUhEeCX9vP/728qv8TJwqKbBtDZY/0uJd0g7rUxfgXD2lCEf58nj5tlt" +
                "xEnhzAu9EDRjolJZGQJBANTmrlAx9BWbZiDuMC/M7LXFvzr1/zKqnMisqm86wN6N" +
                "b6ffDndpcYwLUBt25PiWaLKtwF9m+RCEFx4Hkr9EV1UCQQDEbleM9rYM9kJSnWXl" +
                "6ne//US8N/dpFn+55uHRJL9rPyWEVANmtYQTc0USVojovIbUBAgXNG4eczv8wqdd" +
                "p3tTAkEAwyQlxi/jUCK9+5UW6dllZj84xqxQG3qydmV9WrJ5sgPlwfL76YvmnbyI" +
                "0oOp4AjNMml8GHXj+LV6EvZSFapoeQJAEDolVWnUJEH7vKNwFYxHFD8x/HKLJ81K" +
                "A+uE4CgvAAcZbFMcbNG19X1iSV+Is+FPKhijKneUWUOfwwO5m80ILQJBAMxPWNjH" +
                "5fLIfDUVu89boFGfX9Yg1NX5FypaCt3mf6H16Wub9u7BQt6Y7J4RnVSF0Rh0mxv/" +
                "WdPT+wHRgVaBA90=";
        String PUBLIC_KEY = "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCjXGFj7UX+iiHOOqEkIJiyV24oFYJaQmUvSnMzrsXdoQY/Ov4O3Ds6yT8xZr4e7ViytltbQhtX2u4dBBH088AoYxIJZWWIO/LnXpeo3/OC6WVVLEdy9YaO+hP1IYYCpzRVvHABD9VLpU7LDzsMrTjOOTuU86WTLYhLBfI7spEnjwIDAQAB";

        String str = "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQC/YA9PUKqnEdm9rO4D2fBNxdiG" +
                "pnrPVlcnPbSLOFC73Ma0ICGR1hAOUKqhZErD9ST3CK8jC4yIzwXyb2LvsKymXXoT" +
                "he8KQzjKVfV+Fl/ObrKWR/qgbiN+eK1ttMHE+YN0yqOBwOsun4HgddnR09ebFOl7" +
                "xt4xxIKVMSk8ZQRIuQIDAQAB";

        String pri_sss = "MIICdwIBADANBgkqhkiG9w0BAQEFAASCAmEwggJdAgEAAoGBAK8HaEqzWGmATHuD" +
                "GTsCBzb37bVxdhEIVBgMorFCgjZgA6eXhLc/wZ2XD4PT5f5/a1xYQQma8cCY3pZB" +
                "zwL8tNbnc+pWmUX/2pFWlRQWPSW2H9FTSbuWkSOfEWdvNR1WH4eukZIvXcb9CU5W" +
                "+6YnFchI6eYU/tJ4KCwz7I4C0qe9AgMBAAECgYAjD5DMpfBn8dNgSnqbX2Siljd/" +
                "ySKlds2ho6ZTa8c5rTIOOEPVkWfvcXsiJShFOrD+5o7gpbEXq4erAbO+HXD75sCX" +
                "BzNCt+fzAEwsgy6hYCUSKYOV4eaA82NYjFmjF366G2NLXJ7Qu2ASlSaSiMJVJFiX" +
                "f48JjL4FjQTA5J0xAQJBANbsTNI80paQYw8sOAbxMML9CO7srJkqyhW5ibCGufkE" +
                "qPnw2sSZx8rDdOheYn1DKvQFcSlxQ9ShtRR0Jjpl5TUCQQDQey2q2V8RuGr1hkAR" +
                "4zC4+i1abFvKxPzVi20d9MGRLJ97vNJASl3Y3iXFfDKsEV5VF7Tg0T2ZjKkj8xBl" +
                "FrFpAkEAwEnclYDbfOAj8LBEVFm4ocwYEQPpjIRPF87PVQPFIfm8YRrP8HQR3+Su" +
                "FTRU8/ODW53+1/BBmt0vEOS2SytdPQJBAI6y4W1B3/rHGh74Rz53HVBfnU95P9Mo" +
                "xk58YrHQZ/Wwb3FIqzjqLhZU59Gm0yBHuyPPWDVRwzIov1Ul+CDZSZECQDDOR9ak" +
                "iStyJHJwm6QkdizooK5HQxt9YN6wLWQEtOxQgKHg2bEw7WvvoR5mlDoIvkid0ruw" +
                "IlCpg6nYC4HMUHo=";

        System.out.print(str);
        final  String srcStr="RSA密钥测试";
        byte[] data = srcStr.getBytes("UTF-8");
        PKCS8EncodedKeySpec pkcs8EncodedKeySpec = new PKCS8EncodedKeySpec((new BASE64Decoder()).decodeBuffer(PRIVATE_KEY));
        X509EncodedKeySpec x509EncodedKeySpec = new X509EncodedKeySpec((new BASE64Decoder()).decodeBuffer(PUBLIC_KEY));
        KeyFactory keyFactory = KeyFactory.getInstance("RSA");
        PrivateKey privateKey = keyFactory.generatePrivate(pkcs8EncodedKeySpec);
        PublicKey publicKey = keyFactory.generatePublic(x509EncodedKeySpec);
        //加密
        Cipher cipher = Cipher.getInstance("RSA");
        cipher.init(Cipher.ENCRYPT_MODE,privateKey);
        byte[] encodebytes = cipher.doFinal(data);
        System.out.println("私钥加密后:"+(new BASE64Encoder().encode(encodebytes)));

        //解密
        Cipher cipher1 = Cipher.getInstance("RSA");
        cipher1.init(Cipher.DECRYPT_MODE, publicKey);
        byte[] decodebyte = cipher1.doFinal(encodebytes);
        System.out.println("公钥解密后:" + new String(decodebyte));

        //签名
        Signature signature = Signature.getInstance("SHA1WithRSA");
        signature.initSign(privateKey);
        signature.update(data);
        byte[] signbyte = signature.sign();
        //验签
        Signature signature1 = Signature.getInstance("SHA1WithRSA");
        signature1.initVerify(publicKey);
        signature1.update(data);
        Boolean status = signature1.verify(signbyte);
        System.out.println("验签结果:"+status);

        String testPri = "MIICdgIBADANBgkqhkiG9w0BAQEFAASCAmAwggJcAgEAAoGBAJrYmCarq+70hmF0+8WlmO3g6L5/XoohDDmrPWfzKIaTsZEp0ZsQNHc+o8IQv5Po0G7cQSpM00sfsaHeY5bWOeAhNqcKYBuPKja18bQXynZnnUUbCYd+tMdxv+6Y2yOz9+FxKEiIFe3YJr9XxWakvegfDO7GE2nd+FEgElFIZAVhAgMBAAECgYBz/4PjnEEdrhKpGWCuzIIG2bChXHsvENi+rtg+cfrO7f9cVq6N8hLLraIxdCiAHi1ejyNGE+1JXsHMF/QVAAC0CvgmPSbDZgw98jbKuU8xCfsLzGZzMCLvtkwwS8O3abOs3jgtp2y3XwgDGvoW8Kvy4FVFR3EqrpFJQQVy/FvbQQJBAMn6jSLOTQaae03NyV0RY7dVPHTxn67vdLRfwPmOW/c9ChTRmKV9qiFXllMigCV8NrxSt4IIV+075fgrDB6I3fkCQQDEQuD47vV0Xjdhq63IfpuIrX8QpzWSEtdJv1ETOILRC2vbOvZ9axE8KOd6hvj7ustGCYCnjAQOTT0NzpXTZFypAkAaRfJH/cf9POkfNM6lwZZUCc1kdO3Npq5qrC4BCGikH5eJH76YgGE6Fxeh1tIOjjrcgnIGgylU3b7LamYYLruZAkBpibVE5+siWo/Ze+KF0F9/Dh0oLWKHXI5c3/6PIXJnS4cCayClrO+ltDFWGELHy1kIHpAKiSadMjfEtvSmqm+RAkEAr5Pyyr4Xdn3p6pyMQTidYCE+3UVR8q5DyrhXbjRaJdghGX25jcGeo/qkNqoiJr2IZtEoa0oE8g6hkplm9F8p0w==";

        String testPub = "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCa2Jgmq6vu9IZhdPvFpZjt4Oi+f16KIQw5qz1n8yiGk7GRKdGbEDR3PqPCEL+T6NBu3EEqTNNLH7Gh3mOW1jngITanCmAbjyo2tfG0F8p2Z51FGwmHfrTHcb/umNsjs/fhcShIiBXt2Ca/V8VmpL3oHwzuxhNp3fhRIBJRSGQFYQIDAQAB";

        String valideData = "uniqueId=21127267277355001&businessMoney=1&payerId=&replyId=1201605180000001";
        //加签
        String returnSign = getSign(testPri,valideData);

        //验签
        boolean flag = checkSign(testPub,valideData,returnSign);
        System.out.print("######"+flag);
    }


    public static String getSign(String priKey,String data) throws Exception{
        PKCS8EncodedKeySpec pkcs8EncodedKeySpec = new PKCS8EncodedKeySpec(Base64.decodeBase64(priKey));
        KeyFactory keyFactory = KeyFactory.getInstance("RSA");
        PrivateKey privateKey = keyFactory.generatePrivate(pkcs8EncodedKeySpec);
        Signature signature = Signature.getInstance("SHA1WithRSA");
        signature.initSign(privateKey);
        signature.update(data.getBytes("UTF-8"));
        byte[] signbyte = signature.sign();
        return Base64.encodeBase64String(signbyte);
    }

    public static Boolean checkSign(String pubKey,String data,String signData) throws Exception{
        KeyFactory keyFactory = KeyFactory.getInstance("RSA");
        X509EncodedKeySpec x509EncodedKeySpec = new X509EncodedKeySpec(Base64.decodeBase64(pubKey));
        PublicKey publicKey = keyFactory.generatePublic(x509EncodedKeySpec);
        Signature signature1 = Signature.getInstance("SHA1WithRSA");
        signature1.initVerify(publicKey);
        signature1.update(data.getBytes("UTF-8"));
        return signature1.verify(Base64.decodeBase64(signData));
    }


}
